package com.uroad.jilinpda.activity;

import android.annotation.SuppressLint;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;


import com.uroad.jilinpda.R;
import com.uroad.jilinpda.bleactivation.TopUpCardInfo;
import com.uroad.jilinpda.bleactivation.TopUpUtil;
import com.uroad.jilinpda.common.Base58ETCActivity;
import com.uroad.jilinpda.common.CurrApplication;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.modle.AuthgmMDL;
import com.uroad.jilinpda.modle.ModifyActivationMDL;
import com.uroad.jilinpda.net.JsonUtil;
import com.uroad.jilinpda.util.LogUtils;
import com.uroad.jilinpda.util.PriorityExecutor;
import com.uroad.jilinpda.util.SPEC;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.util.ToastUtil;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.widget.OBULoadingDialog;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.widget.dialog.DialogHelper;


import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import etc.obu.data.CardInformation;
import etc.obu.data.ObuSystemInformation;

public class ETCActivation58GActivity extends Base58ETCActivity {

    @BindView(R.id.ivAnimation)
    ImageView ivAnimation;
    @BindView(R.id.clTitleLayout)
    ConstraintLayout clTitleLayout;
    private AnimationDrawable animationDrawable;
    private String content = "";
    private static final String TAG = "ETCActivationActivity";
    private enum State {
        START,
        CMD_TO_3F00,
        CMD_OBU_SYSTEM_INFO, //obu获取设备系统信息
        CMD_OBU_RANDOM, //obu获取随机数
        CMD_CARD_RANDOM, //获取卡随机数
        CMD_OBU_CAR_INFO, //obu获取车辆信息文件
        CMD_CARD_GET_0016,//获取0016文件
        CMD_CARD_GET_0015,//获取卡号 （0015）
        CMD_CARD_BALANCE,//获取卡余额 （电子钱包）
        CMD_OBU_MODIFY_VEHICLE,
        CMD_OBU_MODIFY_SYSTEM,
        CMD_CARD_MODIFY_0016,
        CMD_CARD_MODIFY_0015,
        CMD_AUTHGM,
        CMD_GM_OBU_MODIFY_SYSTEM,
        CMD_GM_CARD_MODIFY_0015,
        CMD_GM_CARD_MODIFY_0016,
    }
    private State state = State.START;
    private String ticketid = "";
    private String deviceuuid = "";
    private String orderno = "";
    private String cardNo = "";
    private String cardArea = "";
    private String randomObu = "";
    private String randomCard = "";
    private String file0016 = "";
    private String file0015 = "";
    private String cardBalance = "";
    private String mSessionId = "";
    private String filevehicle = "";
    private String fileSystem = "";
    private String seno = "";
    private String startstate = "0";
    private String instructionresps = "";
    private String instructionrespsmac = "";
    private String plateNo = "";
    private String type = "";
    private boolean isActivationSuccess = false;
    /** 是否走国密通道*/
    private boolean isGm = false;
    private OBULoadingDialog loadingDialog;
    private String instructions = "";
    private String instructionsmac = "";
    private boolean isEndSureSuccess = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_etcactivation);
        setTitle("标签激活");
        ButterKnife.bind(this);
        init();
    }
    private void init(){
        ticketid = (String) SPUtils.get(this, GlobalData.sp_ticketid, "");
        loadingDialog = new OBULoadingDialog(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = bundle.getString("type");
            orderno = bundle.getString("orderno");
            if("testing".equals(type)){
                setTitle("标签检测");
                clTitleLayout.setVisibility(View.GONE);
            }else{
                setTitle("标签激活");
                toConnect();
            }
        }
        animationDrawable = (AnimationDrawable) ivAnimation.getDrawable();
        animationDrawable.start();
        resetCard(onResultListener);
    }
    private void toConnect() {
        loadingDialog.setTips("正在连接");
        loadingDialog.show();
    }
    //ETC obu开始第一次读卡 或 PSAM授权完成后开始写卡
    protected void resetCard(final OnResultListener resultListener){
        PriorityExecutor.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //打开天线
                    int result=-1;
                    //打开天线

                    result = CurrApplication.getInstance().openDsrc();
                    LogUtils.i("CMD打开天线：" + result);

                    if (result == 0) {
                        final CardInformation tmpCardInformation = new CardInformation();
                        ObuSystemInformation obuSystemInformation = new ObuSystemInformation();
                        result = CurrApplication.getInstance().getHandsetSDK().findObu(obuSystemInformation, tmpCardInformation);
                        if (result == 0) {
                            ETCActivation58GActivity.this.tmpCardInformation = tmpCardInformation;
                            ETCActivation58GActivity.this.obuSystemInformation = obuSystemInformation;
                            mResultCode = SPEC.EVENT.SUCCESS;
                            //                            runOnUiThread(new Runnable() {
                            //                                @Override
                            //                                public void run() {
                            resultListener.onSuccess(CMD_A5, mResultCode, obuSystemInformation.getSerialNumber());
                            //                            keepAlive.start();
                            //                            isKeepAlive = true;
                            //                                }
                            //                            });
                        } else {
                            mResultCode = SPEC.EVENT.ERROR;
                            final int finalResult = result;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    resultListener.onError("读卡失败:" + finalResult);
                                    CurrApplication.getInstance().closeDsrc();
                                }
                            });
                        }
                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                resultListener.onError("唤醒失败");
                                CurrApplication.getInstance().closeDsrc();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resultListener.onError("读卡异常");
                            CurrApplication.getInstance().closeDsrc();
                        }
                    });
                }
            }
        });
    }

    private final OnResultListener onResultListener = new OnResultListener() {
        @Override
        public void onSuccess(int requestCode, SPEC.EVENT event, String result) {
            if (event == SPEC.EVENT.ERROR) {
                content = "发卡失败";
                cpuError();
                return;
            }
            if (TextUtils.isEmpty(result) || result.length() < 4) {
                content = result;
                cpuError();
                return;
            }
            try {
            switch (requestCode) {
                case CMD_A5:
                    keepAlive.setChannelID(1);//
                    seno = result;
                    LogUtil.i(TAG,"寻卡成功");
                    content = "正在读取设备信息";
                    sendMsg(3);
                    SendCmd(CMD_CARD_0016);
                    break;
                case CMD_CARD_0016://卡0016文件
                    file0016 = result;
                    LogUtils.i("CMD获取0016文件返回："+file0016);
                    if (!TextUtils.isEmpty(file0016)&&file0016.length()>12&&file0016.endsWith("9000")) {
                        //                            file0016 = file0016.substring(8, file0016.length() - 4);
                        state = State.CMD_CARD_GET_0015;
                        //获取卡号（0015文件）
                        SendCmd(CMD_CARD_BALANCE);
                    }else{
                        content = "获取0016文件失败";
                        sendMsg(2);
                    }
                    break;
                case CMD_CARD_BALANCE:
                    cardBalance = TopUpUtil.getCardBalance(result);
                    LogUtils.i("card Balance:" + cardBalance);
                    //获取卡号（0015文件）
                    SendCmd(CMD_CARD_NUMBER);
                    break;
                case CMD_CARD_NUMBER://0015
                    file0015 = result;
                    LogUtils.i("CMD获取0015文件返回："+file0015);
                    if (TextUtils.isEmpty(file0015)) {
                        content = "获取0015文件失败";
                        sendMsg(2);
                        return;
                    }
                    if (file0015.length() > 12) {
                        //                            file0015 = file0015.substring(8, file0015.length() - 4);
                    }
                    //TODO 获取卡号
                    LogUtils.i("0015data:" + result);
                    // 卡网络编号 各省唯一
                    TopUpCardInfo cardInfo = TopUpUtil.getCardNumber(result);
                    cardArea = cardInfo.getCardArea();
                    LogUtils.i("修改前，cardArea:" + cardArea);
                    //                    if (!GlobalData.cardArea.equals(cardArea)) {
                    //                        runOnUiThread(new Runnable() {
                    //                            @Override
                    //                            public void run() {
                    //                                DialogHelper.showComfirmDialog(mContext, "取消", "确定", "激活设备只支持辽通卡",
                    //                                        new ComfirmDialog.DialogOnclick() {
                    //                                            @Override
                    //                                            public void PerDialogclick(ComfirmDialog dialog) {
                    //                                                dialog.dismiss();
                    //                                                finish();
                    //                                            }
                    //                                        }, new ComfirmDialog.DialogOnclick() {
                    //                                            @Override
                    //                                            public void PerDialogclick(ComfirmDialog dialog) {
                    //                                                dialog.dismiss();
                    //                                                finish();
                    //                                            }
                    //                                        });
                    //                            }
                    //                        });
                    //                    }
                    cardNo = cardInfo.getCardNumber();
                    plateNo = cardInfo.getPlateNum();

                    if (isActivationSuccess) {
                        loadingDialog.dismiss();
                        stopObuKeepAlive();
                        showShortToast("激活成功");
//                        String cardNew=cardArea+cardNo;
                        activationSuccess();
                        finish();
                    }else {

                        if (!TextUtils.isEmpty(cardNo)) {
                            String cardType = cardNo.substring(4, 6);
                            if ("23".equals(cardType)) {
                                //                                tvCardType.setText(getResources().getString(R.string.card_type) + "记账卡");
                            } else {
                                //                                tvCardType.setText(getResources().getString(R.string.card_type) + "储值卡");
                            }
                        }
                        SendCmd(CMD_OBU_SYSTEM_INFO);
                    }
                    break;
                case CMD_OBU_SYSTEM_INFO://OBU系统信息 EF01
                    fileSystem = result;
                    LogUtils.i("CMD获取OBU系统信息返回："+fileSystem);
                    if (!TextUtils.isEmpty(fileSystem)&&fileSystem.length()>44) {
                        //fileSystem = fileSystem.substring(8, fileSystem.length() - 4);
                        //合同版本号
                        //contractedition = fileSystem.substring(36, 38);

                        //                             seno = fileSystem.substring(28, 44);
                        //读取车辆信息(DF01-EF01)
                        state = State.CMD_OBU_CAR_INFO;
                        SendCmd(CMD_OBU_CAR_INFO);
                    }else{
                        onError("获取系统信息异常："+fileSystem);
                    }
                    break;
                case CMD_OBU_CAR_INFO://obu车辆信息 DF01-EF01
                    filevehicle = result;
                    LogUtils.i("CMD获取obu车辆信息返回："+filevehicle);
                    if (!TextUtils.isEmpty(filevehicle) && filevehicle.length() > 12) {
                        //                            filevehicle = filevehicle.substring(8, filevehicle.length() - 4);
                        //                        if (GlobalData.isDebug) {
                        //                            orderno = etOrderNo.getText().toString().trim();
                        //                        }
                        cardNo = cardArea + cardNo;
                        if (!TextUtils.isEmpty(type)) {
                            //obu激活
                            /*Bundle bundle = new Bundle();
                            bundle.putString("fileSystem", fileSystem);
                            bundle.putString("fileVehicle", filevehicle);
                            bundle.putString("file0015", file0015);
                            bundle.putString("cardBalance", cardBalance);
                            bundle.putString("obuNo", seno);
                            bundle.putString("randomObu", randomObu);
                            openActivity(OBUQueryInfoActivity.class,bundle);
                            finish();*/
                            SendCmd(CMD_OBU_RANDOM);
                        }else {
                            content = "正在发行设备";
                            sendMsg(3);
                            //查询是否可以激活
                            //                            handler.postDelayed(new Runnable() {
                            //                                @Override
                            //                                public void run() {
                            //                                    content = "正在发行卡片";
                            //                                    sendMsg(3);
                            //                                    toNextStep();
                            //                                }
                            //                            },2000);
//                            obuKeepAlive();
                            doRequest(ActivateWS.canActivate, ActivateWS.canActivateParams(ticketid,
                                    orderno, cardNo, seno), ActivateWS.canActivate);
                        }
                    }else{
                        onError("获取系统信息异常："+fileSystem);
                    }
                    break;
                case CMD_C4:
//                    String c4Data = TopUpUtil.bytes2HexString(result);
                    String c4Data = result;
                    if (!TextUtils.isEmpty(c4Data)) {
                        LogUtil.e("","CMD_C4---" + c4Data);
                        String SE = c4Data.substring(10, 26);
                        String R1 = c4Data.substring(26, 58);
                        String S1 = c4Data.substring(58, c4Data.length() - 2);
                        String A1 = c4Data.substring(c4Data.length() - 2);
                        //国密握手
                        authGm(SE,R1,S1,A1);
                    }else{
                        showShortToast("C4指令执行失败");
                        onError("C4指令执行失败");
                    }
                    break;
                case CMD_C5:
                    /*if (data[0] != (byte) 0xb6) {
                        LogUtil.e("","!=" + 0xb6);
                        return;
                    }*/
                    switch (startstate) {//取随机数
                        case "0":
                            SendCmd(CMD_GM_OBU_RANDOM, instructions + instructionsmac);
                            //                                SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                            break;
                        case "1":
                            SendCmd(CMD_GM_OBU_RANDOM, instructions + instructionsmac);
                            break;
                        case "2":
                            SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                            break;
                        case "3":
                            SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                            break;
                    }
                    break;
                case CMD_GM_OBU_RANDOM:
//                    String gmOBURandom = TopUpUtil.getInstructionResp(data);
                    String gmOBURandom = result;
                    if (!TextUtils.isEmpty(gmOBURandom)) {
                        instructionresps = gmOBURandom.substring(0, gmOBURandom.length() - 8);
                        instructionrespsmac = gmOBURandom.substring(gmOBURandom.length() - 8);
                        state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                        if ("0".equalsIgnoreCase(startstate)) {
                            gmModifyVehicle();
                        } else if ("1".equalsIgnoreCase(startstate)) {
                            gmModifySystem();
                        }
                    }
                    break;
                case CMD_GM_CARD_RANDOM:
//                    String gmCardRandom = TopUpUtil.getInstructionResp(data);
                    String gmCardRandom = result;
                    if (!TextUtils.isEmpty(gmCardRandom)) {
                        instructionresps = gmCardRandom.substring(0, gmCardRandom.length() - 8);
                        instructionrespsmac = gmCardRandom.substring(gmCardRandom.length() - 8);
                        state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                        if ("2".equalsIgnoreCase(startstate)) {
                            gmModify0016();
                        } else if ("3".equalsIgnoreCase(startstate)) {
                            gmModify0015();
                        }
                    }
                    break;
                case CMD_OBU_RANDOM:
                    //                        if (GlobalData.isDebug) {
                    loadingDialog.setTips("读取OBU随机数成功");
                    //                        }
                    //                        randomObu = TopUpUtil.bytes2HexString(data).substring(18, 26);
//                    randomObu = TopUpUtil.getInstructionResp(data);
                    randomObu = result;
                    if (!TextUtils.isEmpty(randomObu)) {
                        randomObu = randomObu.toUpperCase();
                        if (!TextUtils.isEmpty(type)){
                            //obu激活
                            Bundle bundle = new Bundle();
                            bundle.putString("fileSystem", fileSystem);
                            bundle.putString("fileVehicle", filevehicle);
                            bundle.putString("file0015", file0015);
                            bundle.putString("obuNo", seno);
                            bundle.putString("cardBalance", cardBalance);
                            bundle.putString("randomObu", randomObu);
                            openActivity(OBUQueryInfoActivity.class,bundle);
                            loadingDialog.dismiss();
                            finish();
                            return;
                        }
                        if (isEndSureSuccess){
                            issueEnd();
                        }else {
                            modifyVehicle();
//                                startstate = "0";
//                                mSessionId = "d79839614e3aeaac015048a114b1541a";
//                                SendCmd(CMD_OBU_MODIFY_VEHICLE, "8067014404D681003FBCAA4139334D453000000000000001000000000000000000000005000000000000000000000000000000004C3330353136380000000000000000000E34A9F2020f00b400000a00000000000000003b00030700a40000023f0004050084000004");
                        }
                    }
                    break;
                case CMD_GM_OBU_MODIFY_VEHICLE:
//                    String gmVehicleResult = TopUpUtil.getInstructionResp(data);
                    String gmVehicleResult = result;
                    if (!TextUtils.isEmpty(gmVehicleResult)) {
                        instructionresps = gmVehicleResult.substring(0, gmVehicleResult.length() - 8);
                        instructionrespsmac = gmVehicleResult.substring(gmVehicleResult.length() - 8);
                        state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                        gmModifySystem();
                    }
                    break;
                case CMD_GM_OBU_MODIFY_SYSTEM:
//                    String gmSystemResult = TopUpUtil.getInstructionResp(data);
                    String gmSystemResult = result;
                    if (!TextUtils.isEmpty(gmSystemResult)) {
                        instructionresps = gmSystemResult.substring(0, gmSystemResult.length() - 8);
                        instructionrespsmac = gmSystemResult.substring(gmSystemResult.length() - 8);
                        SendCmd(CMD_TO_3F00);
                    }
                    break;
                case CMD_GM_CARD_MODIFY_0016:
                    String gm0016Result = result;
//                    String gm0016Result = TopUpUtil.getInstructionResp(data);
                    if (!TextUtils.isEmpty(gm0016Result)) {
                        instructionresps = gm0016Result.substring(0, gm0016Result.length() - 8);
                        instructionrespsmac = gm0016Result.substring(gm0016Result.length() - 8);
                        state = State.CMD_GM_CARD_MODIFY_0015;
                        gmModify0015();
                    }
                    break;
                case CMD_GM_CARD_MODIFY_0015:
//                    String gm0015Result = TopUpUtil.getInstructionResp(data);
                    String gm0015Result = result;
                    if (!TextUtils.isEmpty(gm0015Result)) {
                        instructionresps = gm0015Result.substring(0, gm0015Result.length() - 8);
                        instructionrespsmac = gm0015Result.substring(gm0015Result.length() - 8);
                        state = State.CMD_OBU_MODIFY_SYSTEM;
                        gmIssueEnd();
                    }
                    break;
                case CMD_OBU_MODIFY_VEHICLE:
//                    String vehicleResult = TopUpUtil.getInstructionResp(data);
                    String vehicleResult = result;
                    if (!TextUtils.isEmpty(vehicleResult)) {
                        instructionresps = vehicleResult;
                        switch (startstate) {
                            case "0":
                            case "1":
                                modifySystem();
                                break;
                            case "2":
                                modify0016();
                                break;
                            case "3":
                                modify0015();
                                break;
                        }

                    }
                    break;
                case CMD_CARD_MODIFY_INFO:
//                    String modifyInfo = TopUpUtil.getInstructionResp(data);
                    String modifyInfo = result;
                    if (!TextUtils.isEmpty(modifyInfo)) {
                        instructionresps = modifyInfo;
                        if ("2".equalsIgnoreCase(startstate)) {
                            modify0016();
                        } else if ("3".equalsIgnoreCase(startstate)) {
                            modify0015();
                        }
                    }
                    break;
                case CMD_OBU_MODIFY_SYSTEM:
//                    String systemResult = TopUpUtil.getInstructionResp(data);
                    String systemResult = result;
                    if (!TextUtils.isEmpty(systemResult)) {
                        keepAlive.setChannelID(2);//改为esam（obu）通道 防止随机数失效
                        //跳转3F00目录
                        SendCmd(CMD_TO_3F00);
                        instructionresps = systemResult;
                    }
                    break;
                case CMD_TO_3F00:
                    //                        randomCard = TopUpUtil.bytes2HexString(data).substring(18, 26);
//                    randomCard = TopUpUtil.getInstructionResp(data);
                    randomCard = result;
                    if (!TextUtils.isEmpty(randomCard)) {
                        randomCard = randomCard.toUpperCase();
                        if (isGm) {
                            state = State.CMD_GM_CARD_MODIFY_0016;
                            gmModify0016();
                        }else {
                            state = State.CMD_CARD_MODIFY_0016;
                            modify0016();
                        }
                    }
                    break;
                case CMD_CARD_MODIFY_0016:
//                    String card0016Result = TopUpUtil.getInstructionResp(data);
                    String card0016Result = result;
                    if (!TextUtils.isEmpty(card0016Result)) {
                        instructionresps = card0016Result;
                        state = State.CMD_CARD_MODIFY_0015;
                        modify0015();
                    }
                    break;
                case CMD_CARD_MODIFY_0015:
                    String card0015Result = result;
//                    String card0015Result = TopUpUtil.getInstructionResp(data);
                    if (!TextUtils.isEmpty(card0015Result)) {
                        instructionresps = card0015Result;
                        state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                        isEndSureSuccess=true;
                        SendCmd(CMD_CARD_0016);
                    }
                    break;
            }
            } catch (Exception e) {
                e.printStackTrace();
                showShortToast("读卡失败");
                finish();
            }
        }
        @Override
        public void onError(String error) {
            if (!TextUtils.isEmpty(error)) {
                content = "写入失败:" + error;
            }else{
                content = "写入失败";
            }
            try{
                LogUtils.i("CMD执行失败：" + content);
                cpuError();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    private void cpuError() {
        //        psamPownDown();
        //        cpuPownDown();
        loadingDialog.dismiss();
        CurrApplication.getInstance().closeDsrc();
        stopObuKeepAlive();
        finish();
        DialogHelper.endLoading();
        ToastUtil.showShort(ETCActivation58GActivity.this, content);
    }
    private void authGm(String SE, String R1, String S1, String A1) {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用国密握手接口");
        //        }
        state = State.CMD_AUTHGM;
        doRequest(ActivateWS.authgm,ActivateWS.authgmParams(
                orderno,seno,SE,R1,S1,filevehicle,fileSystem,file0016,file0015),ActivateWS.authgm);
    }
    //获取国密标签二发更新车辆信息文件
    private void gmModifyVehicle() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统车辆文件接口");
        //        }
        doRequest(ActivateWS.gmModifyVehicle,
                ActivateWS.gmModifyVehicleParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModifyVehicle);
    }

    private void gmModifySystem() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统信息文件接口");
        //        }
        doRequest(ActivateWS.gmModifySystem,
                ActivateWS.gmModifySystemParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModifySystem);
    }
    private void gmModify0016(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0016文件接口");
        //        }else {
        //            loadingDialog.setTips("正在发行卡片");
        //        }
        doRequest(ActivateWS.gmModify0016,
                ActivateWS.gmModify0016Params(mSessionId,randomCard,instructionresps,instructionrespsmac),
                ActivateWS.gmModify0016);
    }

    private void gmModify0015(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0015文件接口");
        //        }
        doRequest(ActivateWS.gmModify0015,
                ActivateWS.gmModify0015Params(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModify0015);
    }

    private void gmIssueEnd(){
        if (GlobalData.isDebug) {
            loadingDialog.setTips("调用完成接口");
        }
        doRequest(ActivateWS.gmIssueEnd,
                ActivateWS.gmIssueEndParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmIssueEnd);
    }
    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(result);
            if (JsonUtil.GetJsonStatu00(jsonObject)) {
                if (ActivateWS.canActivate.equalsIgnoreCase(id)) {
                    //                CanActivateMDL activateMDL = JsonUtil.fromJson(jsonObject, CanActivateMDL.class);
                    //                if (activateMDL != null) {
                    if (isGm) {
                        //发送A6-C4指令
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送C4指令");
                        //                        }
                        SendCmd(CMD_C4);
                    }else{
                        //读取标签车辆文件 读取标签随机数
                        //获取obu系统信息文件（EF01）
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送获取随机数指令");
                        //                        }
                        SendCmd(CMD_OBU_RANDOM);

                    }
                    //                }
                } else if (ActivateWS.authgm.equalsIgnoreCase(id)) {
                    AuthgmMDL authgmMDL = JsonUtil.fromJson(jsonObject, AuthgmMDL.class);
                    if (authgmMDL != null) {
                        startstate = authgmMDL.getStartstate();
                        mSessionId = authgmMDL.getSessionid();
                        if (TextUtils.isEmpty(startstate) || TextUtils.isEmpty(mSessionId)) {
                            loadingDialog.dismiss();
                            showShortToast("获取数据失败，请稍后重试");
                            return;
                        }
                        if ("4".equalsIgnoreCase(startstate)) {
                            gmIssueEnd();
                            return;
                        }
                        instructions = authgmMDL.getInstructions();
                        instructionsmac = authgmMDL.getInstructionsmac();
                        // C5+工作密钥密文+工作密钥校验值（8字节）+MAC密钥密文+MAC密钥校验值（8字节）+Rnd2（16字节）+S2
                        // String workkey, String workkeyMac, String mackey, String
                        // mackeyMac, String random2,String signdata
                        String[] params = new String[6];
                        params[0] = authgmMDL.getWorkkey();
                        // LogUtils.i("workkey:"+params[0]);
                        params[1] = authgmMDL.getWorkkeymac();
                        // LogUtils.i("workkeyMac:"+params[1]);
                        params[2] = authgmMDL.getMackey();
                        // LogUtils.i("mackey:"+params[2]);
                        params[3] = authgmMDL.getMackeymac();
                        // LogUtils.i("mackeyMac:"+params[3]);
                        params[4] = authgmMDL.getRandom2();
                        // LogUtils.i("random2:"+params[4]);
                        params[5] = authgmMDL.getSigndata();
                        // LogUtils.i("signdata:"+params[5]);
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送C5指令");
                        //                        }
                        SendCmd(CMD_C5, params.toString());
                        // mBluetoothLeService.sendVerifyCmd(CMD_C5, params);
                    }else{
                        showShortToast("国密握手失败");
                    }

                    /**国密流程*/
                } else if (ActivateWS.gmModifyVehicle.equalsIgnoreCase(id)) {
                    ModifyActivationMDL vehicleMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (vehicleMDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改车辆信息文件接口");
                        //                        }
                        if (!TextUtils.isEmpty(vehicleMDL.getInstructions())) {
                            SendCmd(CMD_GM_OBU_MODIFY_VEHICLE, vehicleMDL.getInstructions() + vehicleMDL.getInstructionsmac());
                        }else{
                            showLongToast("国密握手返回失败");
                        }
                    }
                } else if (ActivateWS.gmModifySystem.equalsIgnoreCase(id)) {
                    ModifyActivationMDL systemMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (systemMDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改系统信息文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(systemMDL.getInstructions())) {
                            SendCmd(CMD_GM_OBU_MODIFY_SYSTEM, systemMDL.getInstructions() + systemMDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmModify0016.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modify0016MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0016MDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改卡0016文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(modify0016MDL.getInstructions())) {
                            SendCmd(CMD_GM_CARD_MODIFY_0016, modify0016MDL.getInstructions() + modify0016MDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmModify0015.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modify0015MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0015MDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改卡0015文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(modify0015MDL.getInstructions())) {
                            SendCmd(CMD_GM_CARD_MODIFY_0015, modify0015MDL.getInstructions() + modify0015MDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmIssueEnd.equalsIgnoreCase(id)) {
                    isActivationSuccess = true;
                    //获取卡号（0015文件） 查询卡号车牌号
                    SendCmd(CMD_CARD_NUMBER);
                    /**明文*/
                } else if (ActivateWS.modifyVehicle.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modifyVehicleMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modifyVehicleMDL != null) {
                        startstate = modifyVehicleMDL.getStartstate();
                        mSessionId = modifyVehicleMDL.getSessionid();
                        if (TextUtils.isEmpty(startstate) || TextUtils.isEmpty(mSessionId)) {
                            loadingDialog.dismiss();
                            showShortToast("获取数据失败，请稍后重试");
                            return;
                        }
                        if ("4".equalsIgnoreCase(startstate)) {
                            issueEnd();//4：不执行指令，直接调用发行结束
                            return;
                        }
                        if (!TextUtils.isEmpty(modifyVehicleMDL.getInstructions())) {
                            switch (startstate) {
                                case "0":
                                case "1":
                                    //                                    if (GlobalData.isDebug) {
                                    loadingDialog.setTips("发送修改车辆信息文件接口");
                                    //                                    }
                                    SendCmd(CMD_OBU_MODIFY_VEHICLE, modifyVehicleMDL.getInstructions());
                                    break;
                                case "2":
                                case "3":
//                                    SendCmd(CMD_CARD_RANDOM, modifyVehicleMDL.getInstructions());
                                    break;
                            }
                        }else{
                            showShortToast("获取修改车辆信息数据失败");
                        }
                    }else{
                        loadingDialog.dismiss();
                        //                        if (GlobalData.isDebug) {
                        showShortToast("修改车辆信息数据解析失败");
                        //                        }
                    }
                } else if (ActivateWS.modifySystem.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改系统信息文件指令");
                    //                    }
                    ModifyActivationMDL modifySystemMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modifySystemMDL != null) {
                        if (!TextUtils.isEmpty(modifySystemMDL.getInstructions())) {
                            SendCmd(CMD_OBU_MODIFY_SYSTEM, modifySystemMDL.getInstructions());
                        }else{
                            loadingDialog.dismiss();
                            showShortToast("获取修改系统信息数据失败");
                        }
                    }else{
                        loadingDialog.dismiss();
                        //                        if (GlobalData.isDebug) {
                        showShortToast("修改系统信息数据解析失败");
                        //                        }
                    }
                } else if (ActivateWS.modify0016.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改卡0016文件指令");
                    //                    }
                    ModifyActivationMDL modify0016MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0016MDL != null) {
                        if (!TextUtils.isEmpty(modify0016MDL.getInstructions())) {
                            SendCmd(CMD_CARD_MODIFY_0016, modify0016MDL.getInstructions());
                        }else{
                            loadingDialog.dismiss();
                            showShortToast("获取修改卡系统信息数据失败");
                        }
                    }else{
                        loadingDialog.dismiss();
                        showShortToast("修改卡系统信息解析失败");
                    }
                } else if (ActivateWS.modify0015.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改卡0015文件指令");
                    //                    }
                    ModifyActivationMDL modify0015MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0015MDL != null) {
                        if (!TextUtils.isEmpty(modify0015MDL.getInstructions())) {
                            SendCmd(CMD_CARD_MODIFY_0015, modify0015MDL.getInstructions());
                        }else{
                            loadingDialog.dismiss();
                            showShortToast("获取卡发行数据失败");
                        }
                    }else{
                        loadingDialog.dismiss();
                        showShortToast("修改卡发行数据解析失败");
                    }
                } else if (ActivateWS.issueEnd.equalsIgnoreCase(id)) {
                    isActivationSuccess = true;
                    //获取卡号（0015文件） 查询卡号车牌号
                    SendCmd(CMD_CARD_NUMBER);
                }
            }else{
                loadingDialog.dismiss();
                stopObuKeepAlive();
                showShortToast(JsonUtil.GetErrorString(jsonObject, "msg"));
                //                errorUpload(JsonUtil.GetErrorString(jsonObject, "msg"));
                //                showLongToast(JsonUtil.GetErrorString(jsonObject, "msg"));
                //                SendCmd(CMD_C3);
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            loadingDialog.dismiss();
            showShortToast("数据解析失败：" + result);
        }
    }


    @Override
    public void OnHttpFailure(String type, String errorMsg) {
        super.OnHttpFailure(type, errorMsg);
        loadingDialog.dismiss();
        //        showShortToast("系统繁忙，请稍后重试");
        //        SendCmd(CMD_C3);
        showShortToast("服务器异常\nmsg:" + errorMsg);
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        loadingDialog.dismiss();
        //        showShortToast("网络异常，请检查网络");
        //        SendCmd(CMD_C3);
        showShortToast("网络繁忙，请检查网络");
    }

    private void sendMsg(int type) {
        Message message = new Message();
        message.what = type;
        handler.sendMessage(message);
    }
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isFinishing()) {
                int what = msg.what;
                switch (what) {
                    case 1:
//                        loadingDialog.dismiss();
                        showShortToast(content);
                        stopObuKeepAlive();
                        break;
                    case 2:
                        loadingDialog.dismiss();
//                        loadingDialog.setTips(content);
                        stopObuKeepAlive();
                        showLongToast(content);
                        break;
                    case 3:
                        loadingDialog.setTips(content);
                        break;
                }
            }
        }
    };
    private void SendCmd(final int cmd) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SendCmd(cmd, "");
            }
        }, 100);

    }
    //tag 1卡 2obu
    private void SendCmd(int cmd, String params) {
        switch (cmd) {
            case CMD_TO_3F00:
                state = State.CMD_TO_3F00;
                cpuSendTLVCmd(CMD_TO_3F00,1,DIRECT_CMD_TO_3F00,onResultListener);
                break;
            case CMD_CARD_0016:
                state = State.CMD_CARD_GET_0016;
                cpuSendTLVCmd(CMD_CARD_0016,1,DIRECT_CMD_CARD_0016,onResultListener);
                break;
            case CMD_CARD_BALANCE:
                state = State.CMD_CARD_BALANCE;
                cpuSendTLVCmd(CMD_CARD_BALANCE,1,DIRECT_CMD_CARD_BALANCE,onResultListener);
                break;
            case CMD_CARD_NUMBER:
                state = State.CMD_CARD_GET_0015;
                cpuSendTLVCmd(CMD_CARD_NUMBER,1,DIRECT_CMD_CARD_NUMBER,onResultListener);
                break;
            case CMD_OBU_SYSTEM_INFO:
                state = State.CMD_OBU_SYSTEM_INFO;
                cpuSendTLVCmd(CMD_OBU_SYSTEM_INFO,2,DIRECT_CMD_OBU_SYSTEM_INFO,onResultListener);
                break;
            case CMD_OBU_CAR_INFO:
                state = State.CMD_OBU_CAR_INFO;
                cpuSendTLVCmd(CMD_OBU_CAR_INFO,2,DIRECT_CMD_OBU_CAR_INFO,onResultListener);
                break;
            case CMD_OBU_RANDOM:
                state = State.CMD_OBU_RANDOM;
                cpuSendTLVCmd(CMD_OBU_RANDOM,2,DIRECT_CMD_OBU_RANDOM,onResultListener);
                break;
            case CMD_CARD_MODIFY_INFO:
                state = State.CMD_CARD_RANDOM;
                if (!TextUtils.isEmpty(params)) {
                    cpuSendTLVCmd(CMD_CARD_MODIFY_INFO,1, params,onResultListener);
                }else {
                    cpuSendTLVCmd(CMD_CARD_MODIFY_INFO,1,DIRECT_CMD_CARD_RANDOM,onResultListener);
                }
                break;
            case CMD_OBU_MODIFY_VEHICLE:
                state = State.CMD_OBU_MODIFY_VEHICLE;
                if (!TextUtils.isEmpty(params)) {
                    cpuSendTLVCmd(CMD_OBU_MODIFY_VEHICLE, 2, params, onResultListener);
                }else{
                    showShortToast("OBU修改车辆信息指令不能为空");
                    stopObuKeepAlive();
                }
                break;
            case CMD_OBU_MODIFY_SYSTEM:
                state = State.CMD_OBU_MODIFY_SYSTEM;
                if (!TextUtils.isEmpty(params)) {
                    cpuSendTLVCmd(CMD_OBU_MODIFY_SYSTEM,2, params,onResultListener);
                }else{
                    showShortToast("OBU修改系统信息指令不能为空");
                    stopObuKeepAlive();
                }
                break;
            case CMD_CARD_MODIFY_0016:
                state = State.CMD_CARD_MODIFY_0016;
                if (!TextUtils.isEmpty(params)) {
                    cpuSendTLVCmd(CMD_CARD_MODIFY_0016, 1, params, onResultListener);
                }else{
                    showShortToast("卡片修改0016信息指令不能为空");
                    stopObuKeepAlive();
                }
                break;
            case CMD_CARD_MODIFY_0015:
                state = State.CMD_CARD_MODIFY_0015;
                if (!TextUtils.isEmpty(params)) {
                    cpuSendTLVCmd(CMD_CARD_MODIFY_0015, 1, params, onResultListener);
                }else{
                    showShortToast("片修改0015信息指令不能为空");
                    stopObuKeepAlive();
                }
                break;
        }
    }
    private void activationSuccess() {
        Bundle bundle = getIntent().getExtras();
        bundle.putString("plateNo", plateNo);
        bundle.putString("cardNo",cardNo);
        openActivity(ETCActivationSuccessActivity.class, bundle);
    }
    //获取明文标签二发更新车辆信息文件
    private void modifyVehicle() {
        if (GlobalData.isDebug) {
            ToastUtil.showShort(this,"调用修改系统车辆文件接口");
        }
        doRequest(ActivateWS.modifyVehicle,
                ActivateWS.modifyVehicleParams(orderno, randomObu,filevehicle,fileSystem,
                        file0016,file0015,seno,deviceuuid,ticketid),
                ActivateWS.modifyVehicle);
    }

    private void modifySystem() {
        if (GlobalData.isDebug) {
            ToastUtil.showShort(this,"调用修改系统信息文件接口");
        }
        doRequest(ActivateWS.modifySystem,
                ActivateWS.modifySystemParams(mSessionId, instructionresps),
                ActivateWS.modifySystem);
    }

    private void modify0016(){
        //TODO
        if (GlobalData.isDebug) {
            ToastUtil.showShort(this,"调用修改卡0016文件接口");
        }else {
            ToastUtil.showShort(this,"正在发行卡片");
        }
        doRequest(ActivateWS.modify0016,
                ActivateWS.modify0016Params(mSessionId, randomCard, instructionresps),
                ActivateWS.modify0016);
    }

    private void modify0015(){
        if (GlobalData.isDebug) {
            ToastUtil.showShort(this,"调用修改卡0015文件接口");
        }
        doRequest(ActivateWS.modify0015,
                ActivateWS.modify0015Params(mSessionId, instructionresps),
                ActivateWS.modify0015);
    }

    private void issueEnd(){
        if (GlobalData.isDebug) {
            ToastUtil.showShort(this,"调用完成接口");
        }
        /*doRequest(ActivateWS.issueEnd,
                ActivateWS.issueEndParams(ticketid,mSessionId, instructionresps,filevehicle,fileSystem,file0016,file0015,randomObu),
                ActivateWS.issueEnd);*/
        isActivationSuccess = true;
        //获取卡号（0015文件） 查询卡号车牌号
        SendCmd(CMD_CARD_NUMBER);
    }
}
